import numpy
import paddle
import paddle.fluid as fluid
import os
import matplotlib.pyplot as plt

BATCH_SIZE = 20
BUF_SIZE = 500
train_reader = paddle.batch(
    paddle.reader.shuffle(
        paddle.dataset.uci_housing.train(),
        buf_size=BUF_SIZE
    ),batch_size=BATCH_SIZE
)

test_reader = paddle.batch(
    paddle.reader.shuffle(
        paddle.dataset.uci_housing.test(),
        buf_size=BUF_SIZE
    ),batch_size=BATCH_SIZE
)
# 曼哈顿房价的数据集只有506个数据，每个数据大概是13列
# train_reader = paddle.dataset.uci_housing.train()
# sample = next(train_reader())
# print(sample)

x = fluid.layers.data(name='x',shape=[13],dtype='float32')
y = fluid.layers.data(name='y',shape=[1],dtype='float32')
pred_y = fluid.layers.fc(input=x,size=1,act=None)
cost = fluid.layers.square_error_cost(input=pred_y,label=y)
avg_cost = fluid.layers.mean(cost)
optimizer = fluid.optimizer.SGDOptimizer(learning_rate=0.001)
opts = optimizer.minimize(avg_cost)

test_program = fluid.default_main_program().clone(for_test=True)

USE_CUDA = False
place = fluid.CUDAPlace(0) if USE_CUDA else fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(program=fluid.default_startup_program())
# 这一步已经把数据包括输入和输出，都给了feeder了，所以下面就不需要传下x和y了，直接就传feeder就够了
feeder = fluid.DataFeeder(feed_list=[x,y],place=place)
iter = 0
iters = []
train_costs = []

def drwa_train_process(iters,train_costs):
    title = 'draw cost'
    plt.title(title,fontsize = 24)
    plt.xlabel('iter',fontsize = 14)
    plt.ylabel('cost',fontsize = 14)
    plt.plot(iters,train_costs,color='red',label='train_cost')
    plt.grid()
    plt.show()

EPOCH_NUM = 500
model_dir = 'D:\myPaddle\model\mytrain.model'

for pass_id in range(EPOCH_NUM):
    train_cost = 0
    for batch_id,data in enumerate(train_reader()):
        train_cost = exe.run(program=fluid.default_main_program(),
                             feed=feeder.feed(data),
                             fetch_list=[avg_cost])
        if batch_id%50==0:
            print('Pass_id:%d,Cost:%0.5f'%(batch_id,train_cost[0][0]))
        iter += BATCH_SIZE
        iters.append(iter)
        train_costs.append(train_cost[0][0])

    test_cost = 0
    for batch_id,data in enumerate(test_reader()):
        test_cost = exe.run(program=test_program,
                            feed=feeder.feed(data),
                            fetch_list=[avg_cost])
    print('Test:%d,Cost:%0.5f'%(pass_id,test_cost[0][0]))

#     保存模型
if not os.path.exists(model_dir):
    os.makedirs(model_dir)

print('保存到%s'%model_dir)
fluid.io.save_inference_model(model_dir,
                              ['x'],
                              [pred_y],
                              exe)
drwa_train_process(iters,train_costs)







